package context;

import common.tree.Node;
import entity.User;
import sun.misc.BASE64Encoder;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by asus on 2017/6/17.
 */
public class LoginUserCache {
    private static Map<String, User> cache=new HashMap<>();
    private static Map<String,List<Node>> userAccordionMap=new ConcurrentHashMap<>();

    public static void put(User user){
        cache.put(user.getName(),user);
        UserContext.setCurrent(user);
        System.out.println("usercache put操作，当前user上下文对象是："+UserContext.getCurrent().getUser());
    }

    public static User get(String username){
        return cache.get(username);
    }

    public static void setCookie(User user){
        int expire=1800;
        String source=user.getName()+"$"+user.getPwd();
        String res=getBase64(source);
        Cookie cookie=new Cookie("auth",res);
        cookie.setMaxAge(expire);
        ResponseContext.getCurrent().addCookie(cookie);
    }

    public static void remove(String username){
        cache.remove(username);
        Cookie cookie=new Cookie("auth",null);
        ResponseContext.getCurrent().addCookie(cookie);
        UserContext.setCurrent(null);
    }

    public static void setAccorions(String username ,List<Node> nodes){
        userAccordionMap.put(username, nodes);
    }

    public static List<Node> getAccorions(String username ){
        return userAccordionMap.get(username);
    }

    public static String getBase64(String str){
        byte[] b=null;
        String s=null;
        try{
            b = str.getBytes("utf-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        if(b != null){
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }
}
